﻿using Microsoft.Extensions.Primitives;

namespace LocalTest.Web.Extensions;

public static class WebExt
{
    public static void UseUrlEncodeDataKey(this IApplicationBuilder builder)
    {
        builder.Use((context, next) =>
        {
            if (context.Request is not { ContentType: "application/x-www-form-urlencoded", Method: "POST" or "PUT" })
            {
                return next();
            }

            var dict = new Dictionary<string, StringValues>();
            foreach (var kv in context.Request.Form.ToDictionary())
            {
                String newKey = kv.Key;
                if (kv.Key.Contains("_"))
                {
                    var parts = kv.Key.Split("_");
                    var select = parts.Skip(1).Select((p) =>
                    {
                        char[] chars = p.ToCharArray();
                        chars[0] = char.ToUpper(chars[0]);
                        return new string(chars);
                    }).ToList();
                    select.Insert(0, parts[0]);
                    newKey = string.Join("", select);
                }

                dict.Add(newKey, kv.Value);
            }

            context.Request.Form = new FormCollection(dict);

            return next();
        });
    }
}